/**
 iTextUploader
 (C) 2008 MyselftDev (myselftdev@gmail.com)
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Revision: $Id: main.m 112 2009-04-16 18:12:14Z myselftdev $ */

#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>

#import "../PreferencesData.h"

BOOL startup();
BOOL loadService();
BOOL unloadService();

BOOL startup()
{
	PreferencesData *data = [ [PreferencesData alloc] init];
	BOOL enabled = [[data getData:@"AutomaticUpload"] boolValue];
	[data release];
	
	if(!enabled)
	{
		NSLog(@"Automatic upload disabled");
		[data release];
		return NO;
	}
	else
	{
		return loadService();
	}
	
	return NO;
}

BOOL loadService()
{
	int result = system([[NSString stringWithFormat:@"launchctl load -F %s", LAUNCHD_FILE] UTF8String]);
	NSLog(@"Result: %d", result);
	
	return YES;
}

BOOL unloadService()
{
	int result = system([[NSString stringWithFormat:@"launchctl unload -F %s", LAUNCHD_FILE] UTF8String]);
	NSLog(@"Result: %d", result);
	
	return YES;
}

int main(int argc, char *argv[])
{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	// This is run at startup as root. We must set up launchctl file here
	if(argc > 1)
	{
		if(!strcmp(argv[1],"startup"))
		{
			NSLog(@"Startup");
			startup();
		}
		else if(!strcmp(argv[1],"load"))
		{
			NSLog(@"Loading service");
			loadService();
		}
		else if(!strcmp(argv[1],"unload"))
		{
			NSLog(@"Unloading service");
			unloadService();
		}
	}
	
	[pool drain];
	
	return 0;
}
